package com.inews.base.security.filter;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.inews.base.security.Constants;
import com.inews.base.security.repository.SecurityDao;
import com.inews.base.security.service.SecOrgService;
import com.inews.base.security.vo.SecurityUserDetail;
import com.inews.base.utils.InewsUtils;
import com.inews.business.entity.TblBaseResource;


/**
 * 该类的主要作用是为Spring Security提供一个经过用户认证后的UserDetails
 *
 */
@Component
public class UserDetailsManager implements UserDetailsService {

	private static final Logger logger = Logger.getLogger(UserDetailsManager.class);

	@Autowired
	private SecurityDao baseSysDao;
	@Autowired
	private SecOrgService secOrgService;

	@Override
	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException, DataAccessException {
		if (InewsUtils.isEmpty(userName)) {
			logger.error("用户名不能为空");
			throw new BadCredentialsException("用户名不能为空");
		}
		if (userName.getBytes().length > 50) {
			logger.error(userName + ": 用户名过长 ");
			throw new UsernameNotFoundException("用户名过长");
		}
		List<SecurityUserDetail> users = null;
		try {
			users = baseSysDao.getBaseUserByLoginName(userName);
		} catch (Exception e) {
			e.printStackTrace();
			throw new DataAccessResourceFailureException("database.error");
		}
		if (InewsUtils.isEmpty(users)) {
			throw new UsernameNotFoundException("no user found with name '"
					+ userName + "'");
		}
		if (users.size() > 1) {
			throw new IncorrectResultSizeDataAccessException(
					"More than one user found with name '" + userName + "'", 1);
		}
		List<TblBaseResource> resources = null;
		try {
			resources = baseSysDao.getBaseResourceByLoginName(userName);
		} catch (Exception e) {
			throw new DataAccessResourceFailureException("database.error");
		}
		
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (int i = 0; i < resources.size(); i++) {
			String resourceId = resources.get(i).getResourceId();
			GrantedAuthority authority = new GrantedAuthorityImpl(resourceId);
		    authorities.add(authority);
		}
		SecurityUserDetail user = users.get(Constants.ZERO);
		user.setAuthorities(authorities);
		List<String> orgIdList = secOrgService.findSubOrgList(user.getOrgId());
		user.setChildBrhIds(orgIdList);
		return user;
	}

}
